import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

import 'global.dart';
import 'langs/translation_service.dart';
import 'routes/app_pages.dart';
import 'services/services.dart';
import 'utils/utils.dart';

Future<void> main() async {
  await Global.init();

  runApp(
    ScreenUtilInit(
      designSize: const Size(375, 812),
      builder: (context, widget) => RefreshConfiguration(
        headerBuilder: () => const ClassicHeader(),
        footerBuilder: () => const ClassicFooter(),
        hideFooterWhenNotFull: true,
        headerTriggerDistance: 80,
        maxOverScrollExtent: 100,
        footerTriggerDistance: 150,
        child: GetMaterialApp.router(
          title: 'News',
          theme: AppTheme.light,
          debugShowCheckedModeBanner: false,
          // initialRoute: AppPages.INITIAL,
          logWriterCallback: (String value, {bool isError = false}) {
            if (isError || Get.isLogEnable) print('GETX:$value');
          },
          getPages: AppPages.routes,
          builder: EasyLoading.init(),
          localizationsDelegates: const [
            GlobalMaterialLocalizations.delegate,
            GlobalWidgetsLocalizations.delegate,
            GlobalCupertinoLocalizations.delegate,
          ],
          translations: TranslationService(),
          supportedLocales: ConfigStore.to.languages,
          // 你的翻译
          locale: ConfigStore.to.locale,
          // 将会按照此处指定的语言翻译
          fallbackLocale: TranslationService.fallbackLocale,
          // 添加一个回调语言选项，以备上面指定的语言翻译不存在
          enableLog: true,
          routerDelegate: _createDelegate(),
        ),
      ),
    ),
  );
}

GetDelegate _createDelegate() {
  return GetDelegate(
    pages: AppPages.routes,
    navigatorObservers: <NavigatorObserver>[
      GetObserver(null, Routing()),
    ],
    pickPagesForRootNavigator: (currentNavStack) {
      final actives = Get.rootController.rootDelegate.activePages;
      final pages = <GetPage>[];
      for (var p in actives) {
        if (p != currentNavStack && p.route?.maintainState != true) {
          continue;
        }
        final q = p.currentTreeBranch.lastWhere(
            (e) => e.participatesInRootNavigator == true,
            orElse: () => p.route!);
        if (pages.contains(q)) {
          pages.remove(q);
        }
        pages.add(q);
      }
      Get.log('picked root pages: ${pages.map((e) => e.name)}');
      return pages;
    },
  );
}
